{
 "cells": [
  {
   "cell_type": "markdown",
   "source": [
    "# Maximum Likelihood Estimation\n",
    "\n",
    "Stan provides optimization algorithms which find modes of the density specified by a Stan program.\n",
    "Three different algorithms are available:\n",
    "a Newton optimizer, and two related quasi-Newton algorithms, BFGS and L-BFGS.\n",
    "The L-BFGS algorithm is the default optimizer.\n",
    "Newton’s method is the least efficient of the three, but has the advantage of setting its own stepsize."
   ],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "source": [
    "In this example we use the CmdStan example model\n",
    "[bernoulli.stan](https://github.com/stan-dev/cmdstanpy/blob/master/test/data/bernoulli.stan)\n",
    "and data file\n",
    "[bernoulli.data.json](https://github.com/stan-dev/cmdstanpy/blob/master/test/data/bernoulli.data.json>)\n",
    "\n",
    "The `CmdStanModel` class method  `optimize` returns a `CmdStanMLE` object\n",
    "which provides properties to retrieve the estimate of the\n",
    "penalized maximum likelihood estimate of all model parameters:\n",
    "\n",
    "- `column_names`\n",
    "- `optimized_params_dict`\n",
    "- `optimized_params_np`\n",
    "- `optimized_params_pd`\n",
    "\n",
    "In the following example, we instantiate a model and do optimization using the default CmdStan settings:"
   ],
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "source": [
    "import os\n",
    "from cmdstanpy import CmdStanModel, cmdstan_path\n",
    "    \n",
    "bernoulli_dir = os.path.join(cmdstan_path(), 'examples', 'bernoulli')\n",
    "stan_file = os.path.join(bernoulli_dir, 'bernoulli.stan')\n",
    "data_file = os.path.join(bernoulli_dir, 'bernoulli.data.json')\n",
    "\n",
    "# instantiate, compile bernoulli model\n",
    "model = CmdStanModel(stan_file=stan_file)\n",
    "\n",
    "# run CmdStan's otpimize method, returns object `CmdStanMLE`\n",
    "mle = model.optimize(data=data_file)\n",
    "print(mle.column_names)\n",
    "print(mle.optimized_params_dict)\n",
    "mle.optimized_params_pd"
   ],
   "outputs": [],
   "metadata": {}
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}